<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script>
    // resolve()  reject()  all()  race()  done()  finally()

    // resolve() 能将现有的任何对象转换成promise对象
    let p = Promise.resolve('foo');
    console.log(p);
    let p2 = new Promise(resolve => resolve('foo')); // 等价
    p.then((data) => {
        console.log(data);
    })

    // 应用：一些游戏类的素材比较多，等待图片、flash、静态资源文件 都加载完成才进行页面的初始化
    let promise1 = new Promise((resolve,reject) => {});
    let promise2 = new Promise((resolve,reject) => {});
    let promise3 = new Promise((resolve,reject) => {});

    let p4 = Promise.all([promise1,promise2,promise3]);
    p4.then(() => {
       // 三个都成功 才成功
    }).catch(err => {
        // 如果有一个失败 则失败
    });

    // race() 某个异步请求设置超时时间，并且在超时后执行相应的操作
    // 1.请求图片资源
    function requestImg(imgSrc){
        return new Promise((resolve,reject) => {
            const img = new Image();
            img.onload = function (){
                resolve(img);
            }
            img.src = imgSrc;
        });
    }

    function timeout(){
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                reject(new Error('图片请求超时'));
            },6000);
        })
    }
    // 两个同时进行，看哪个先返回
    Promise.race([requestImg('https://img0.baidu.com/it/u=600722015,3838115472&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750'),timeout()]).then(data => {
        console.log(data);
        document.body.appendChild(data);
    }).catch(err => {
        console.log(err);
    });
</script>
</body>
</html>